//获取地址栏参数
function getParams() {
    var name, value;
    var str = location.href;
    var num = str.indexOf("?");
    str = str.substr(num + 1);
    var arr = str.split("&");
    var request = {};
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = decodeURIComponent(arr[i].substr(num + 1));
            request[name] = value;
            //console.log(request[name]);
        }
    }
    return request;
}

//数组去重。arr是要过滤的数据，arrField是要对比的数组中的字段
function unique(arr, arrField) {
    //遍历arr,同时创建结果数组result
    for (var i = 0, result = []; i < arr.length; i++) {
        //遍历结果数组result
        for (var j = 0; j < result.length; j++) {
            //如果result中有一个元素等于arr[i],就退出循环
            //说明arr[i]，是一个重复的元素
            if (result[j][arrField] === arr[i][arrField]) {
                layer.msg('请勿提交重复数据，请检查数据！', { time: 1000 });
                return false;
            }
        }//遍历结束
        //如果j等于result的length，就把arr[i],压入数组result
        //j等于result的length,说明遍历到了最后，也就是没有找到相同的元素
        if (j === result.length) {
            result[result.length] = arr[i];
        }
    }
    return result;//返回result
}


//根据返回数据，改变数组的键值
// var data = [
//     { id: "1", roleId: "666", roleName: "系统管理员", roleDesc: "1" },
//     { id: "2", roleId: "999", roleName: "医务科", roleDesc: "1" }];

// //获取数组每个对象中data已有的键值的个数
// var fieldLen = Object.getOwnPropertyNames(data[0]);

function changeKeys(keys1, keys2, data) {
    var result = [];
    for (var row in data) {
        var r = {};
        for (var i = 0; i < keys1.length; i++) {
            var d = data[row];
            r[keys1[i]] = d[keys2[i]];

        }
        result.push(r);
    }
    return result;
}

// changeKeys(['id', 'uid', 'name', 'desc'], fieldLen, data);




//根据文件字节数，换算单位
function getFileSize(fileByte) {
    var fileSizeByte = fileByte;
    var fileSizeMsg = "";
    if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
    else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
    else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
    else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) fileSizeMsg = "1GB";
    else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    else fileSizeMsg = "文件超过1TB";
    return fileSizeMsg;
}



// 获取两个时间（格式为yyyy-mm-dd）之间的所有时间(不包括开始时间和结束时间)
function dataScope(value1, value2) {
    var getDate = function (str) {
        var tempDate = new Date();
        var list = str.split("-");
        tempDate.setFullYear(list[0]);
        tempDate.setMonth(list[1] - 1);
        tempDate.setDate(list[2]);
        return tempDate;
    }
    var date1 = getDate(value1);
    var date2 = getDate(value2);
    if (date1 > date2) {
        var tempDate = date1;
        date1 = date2;
        date2 = tempDate;
    }
    date1.setDate(date1.getDate() + 1);
    var dateArr = [];
    var i = 0;
    while (!(date1.getFullYear() == date2.getFullYear()
        && date1.getMonth() == date2.getMonth() && date1.getDate() == date2
            .getDate())) {
        var dayStr = date1.getDate().toString();
        if (dayStr.length == 1) {
            dayStr = "0" + dayStr;
        }
        dateArr[i] = date1.getFullYear() + "-" + "0" + (date1.getMonth() + 1) + "-"
            + dayStr;
        i++;
        date1.setDate(date1.getDate() + 1);
    }
    return dateArr;
}

var result = dataScope('2019-02-26', '2019-03-02');
console.log(result)
// 打印结果为：["2019-02-27", "2019-02-28", "2019-03-01"]


// 获取两个时间（格式为yyyy-mm-dd)，之间的所有日期时间(包含开始时间和结束时间)
function getAllDate(begin, end) {
    Date.prototype.format = function () {
        var s = '';
        var mouth = (this.getMonth() + 1) >= 10 ? (this.getMonth() + 1) : ('0' + (this.getMonth() + 1));
        var day = this.getDate() >= 10 ? this.getDate() : ('0' + this.getDate());
        s += this.getFullYear() + '-'; // 获取年份。
        s += mouth + "-"; // 获取月份。
        s += day; // 获取日。
        return (s); // 返回日期。
    };
    var arr = [];
    var ab = begin.split("-");
    var ae = end.split("-");
    var db = new Date();
    db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
    var de = new Date();
    de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);
    var unixDb = db.getTime() - 24 * 60 * 60 * 1000;
    var unixDe = de.getTime() - 24 * 60 * 60 * 1000;
    for (var k = unixDb; k <= unixDe;) {
        //console.log((new Date(parseInt(k))).format());
        k = k + 24 * 60 * 60 * 1000;
        arr.push((new Date(parseInt(k))).format());
    }
    return arr;
}
console.log(getAllDate('2019-02-26', '2019-03-02'));
// 打印结果为：["2019-02-26", "2019-02-27", "2019-02-28", "2019-03-01", "2019-03-02"]


// 得到任意月份的最后一天
function getLastDay(y, m) {
    var dt = new Date(y, m, 1);
    cdt = new Date(dt.getTime() - 1000 * 60 * 60 * 24);
    var month = Number(cdt.getMonth()) + 1;
    if (month < 10) {
        month = '0' + month;
    }
    return cdt.getFullYear() + "-" + month + "-" + cdt.getDate();
}
// console.log(getLastDay("2019","02"));



/*
* 取两个年月时间间隔的所有年月时间
* */
function getYearAndMonth(start, end) {
    var startDate = new Date(Date.parse(start + '-01'));
    var endDate = new Date(Date.parse(end + '-01'));
    var startY = startDate.getFullYear();
    var endY = endDate.getFullYear();
    var xItems = []
    for (var y = startY; y <= endY; y++) {
        var startM = 1;
        var endM = 12;
        if (y == startY) {
            startM = startDate.getMonth() + 1;
        }
        if (y == endY) {
            endM = endDate.getMonth() + 1;
        }
        for (var m = startM; m <= endM; m++) {
            xItems.push(y + '-' + m);
        }
    }
    return xItems;
}


/*
* 设置未选择时的默认时间范围，取当前日期的前30天日期
* */
function setDefaultDates() {
    var date = new Date();
    var currentYear = date.getFullYear();
    var currentMonth = date.getMonth() + 1;
    var currentDate = date.getDate();
    var pDate = new Date(date - 1000 * 60 * 60 * 24 * 30);//最后一个数字30可改，30天的意思
    var previousYear = pDate.getFullYear();
    var previousMonth = pDate.getMonth() + 1;
    var previousDate = pDate.getDate();
    if (currentMonth < 10) {
        currentMonth = '0' + currentMonth;
    }
    if (currentDate < 10) {
        currentDate = '0' + currentDate;
    }
    if (previousMonth < 10) {
        previousMonth = '0' + previousMonth;
    }
    if (previousDate < 10) {
        previousDate = '0' + previousDate;
    }
    $("#dateInput1").val(previousYear + '-' + previousMonth + '-' + previousDate);
    $("#dateInput2").val(currentYear + '-' + currentMonth + '-' + currentDate);
}


/* 
*将时间戳转换为正常日期
*/
function add0(m) { return m < 10 ? '0' + m : m }
function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}


/*
*将对象转化为数组
 */
function ArrData(res) {
    let Arr = []
    for (let i in res) {
        Arr.push(res[i])
    }
    return Arr
}


/**
* 当前日期是本年的第几周. 从 0 开始
 */
Date.prototype.getWeekOfYear = function () {
    var today = this;
    var firstDay = new Date(today.getFullYear(), 0, 1);
    var dayOfWeek2 = firstDay.getDay() === 0 ? 7 : firstDay.getDay();
    var mondayOfSecondWeek = new Date(firstDay.getTime() + (8 - dayOfWeek2) * 24 * 3600 * 1000);
    var num = (today.getTime() - mondayOfSecondWeek.getTime()) / (24 * 3600 * 1000);
    return Math.floor(num / 7) + 1;
};


/**
* 根据字段排序
* @param arr
* @param agrs
* @return {Array}
*/
var sort = function (arr, agrs) {
    for (var j = 0; j < arr.length - 1; j++) {
        //两两比较，如果前一个比后一个大，则交换位置。
        for (var i = 0; i < arr.length - 1 - j; i++) {
            if (arr[i][agrs] < arr[i + 1][agrs]) {
                var temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }
    return arr
};


/**
 * 将Array类型的数据转换为类似Java的Map的Object
                 * @param arr
                 * @param key
                 * @returns {{}}
                 */
function convertArrayToObject(arr, key) {
    var result = {};
    var keyValue;
    for (var i = 0, len = arr.length; i < len; i++) {
        keyValue = arr[i][key];
        if (keyValue !== undefined) {
            result[keyValue] = arr[i];
        }
    }
    return result;
}


/**
* 将类似Java的Map的Object对象转换为Array,并提供排序.
*
* eg1. object = {a:1,b:3} => [1,3]
* eg2. object = {a:[1,2],b:[3,4]} => [1,2,3,4]
*
*
* @param object
* @param sortKey   用来排序的key
* @param isAsc     true升序,false降序
* @return {Array}
*/
function convertObjectToArray(object, sortKey, isAsc) {
    var result = [];
    if (!object) {
        return result;
    }
    for (var pro in object) {
        if (object.hasOwnProperty(pro)) {
            if ($.isArray(object[pro])) {
                result = result.concat(object[pro]);
            } else {
                result.push(object[pro]);
            }
        }
    }
    //排序
    if (result.length > 0 && sortKey !== undefined) {
        if (isAsc === undefined) {
            isAsc = true;
        }
        var _sort = 0;
        if (isAsc) {
            result.sort(function (a, b) {
                if (!a[sortKey] && !b[sortKey]) {
                    _sort = 0;
                } else if (!a[sortKey]) {
                    _sort = 1;
                } else if (!b[sortKey]) {
                    _sort = -1;
                } else {
                    _sort = a[sortKey] > b[sortKey] ? -1 : 1;
                }
                return _sort;
            });
        } else {
            result.sort(function (a, b) {
                if (!a[sortKey] && !b[sortKey]) {
                    _sort = 0;
                } else if (!a[sortKey]) {
                    _sort = -1;
                } else if (!b[sortKey]) {
                    _sort = 1;
                } else {
                    _sort = a[sortKey] < b[sortKey] ? -1 : 1;
                }
                return _sort;
            });
        }
    }
    return result;
}



/*
* 数组根据时间字段去重
*(a.time，示例中现在根据time这个字段进行的去重处理)
*/
function unique(arr) {
    const res = new Map();
    return arr.filter((a) => !res.has(a.time) && res.set(a.time, 1))
}



/*
*动态生成一组控件之后，勾选复选框删除时的操作（可单个或多个删除）
*zqCheckboxList --- 勾选的复选框
*zqRelList --- 控件的值
*/
function deleteKongjian() {
    if (this.zqCheckboxList.length > 0) {
        for (var i = 0; i < this.zqCheckboxList.length; i++) {
            for (var j = 0; j < this.zqRelList.length; j++) {
                if (this.zqCheckboxList[i] == this.zqRelList[j]) {
                    this.zqRelList.splice(j, 1);
                    this.zqCheckboxList.splice(this.zqCheckboxList.indexOf(this.zqCheckboxList[i]), 1);
                    j = j - 1;
                    i = i - 1;
                }
            }
        }
    } else {
        this.$message("请选择要删除的项");
    }
}


/**
 * 计算两个坐标点的角度
 * @param {Object} firstPoint 第一个经纬度坐标点
 * @param {Object} nextPoint 下一个经纬度坐标点
 * @returns {Number} 角度值
 */
function getAngle(firstPoint, nextPoint) {
  if (!(firstPoint && nextPoint)) {
    return 0
  }

  let dRotateAngle = Math.atan2(
    Math.abs(firstPoint.LGTD - nextPoint.LGTD),
    Math.abs(firstPoint.LTTD - nextPoint.LTTD)
  )
  if (nextPoint.LGTD >= firstPoint.LGTD) {
    if (nextPoint.LTTD >= firstPoint.LTTD) {
    } else {
      dRotateAngle = Math.PI - dRotateAngle
    }
  } else {
    if (nextPoint.LTTD >= firstPoint.LTTD) {
      dRotateAngle = 2 * Math.PI - dRotateAngle
    } else {
      dRotateAngle = Math.PI + dRotateAngle
    }
  }
  dRotateAngle = (dRotateAngle * 180) / Math.PI
  return dRotateAngle
}


/*
* 获取两个数组中不同的元素
*/
function getArrDifference(arr1, arr2) {
  return arr1.concat(arr2).filter(function(v, i, arr) {
    return arr.indexOf(v) === arr.lastIndexOf(v)
  })
}


/*
* 数组元素去重
*/
export function unique(arr) {
  const res = new Map()
  return arr.filter((a) => !res.has(a) && res.set(a, 1))
}